# 代码运行异常会抛错并终止代码
# def func():
#     if 1/0:
#         print("abc")
#     else:
#         print("efg")
#
# func()
# print("运行结束!")

# 异常处理, try  except
# try后面一定需要使用except/finally,如果不适用,代码机构就有问题,不能运行
# try分支里面,报错之前的代码会正常运行
# num = 1
# try:
#     1 / 0
#     num += 1
#     print("代码运行成功")
# except:
#     print("代码运行报错了")
# # try里面的代码运行成功时,会执行else里面的代码,运行except就不会运行else里面的代码
# else:
#     print("num值被改变了")
# # 不管try里面的代码是否抛错,最后后悔运行
# finally:
#     print("运行finally")

# print(num)
# print("代码运行结束")

# def func():
#     try:
#         pass
#     except:
#         print("代码运行报错了")
#     else:
#         print("执行else")
#         return 1
#
# print(func())

# 捕获异常
# import traceback
# num = 1
# try:
#     open("C:\\abc")
#     num += 1
# except Exception as e:
#     print(e)

# traceback抛错详细信息
import traceback

try:
    1/0
except:
    # traceback.print_exc(file=open('error.txt',"w+"))	# 打印异常信息
    error=traceback.format_exc()	# 返回异常信息
    print("代码异常信息：\n",error)